package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1. 校验参数是否又数据-没有数据需要返回501
        if(null == dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 对分页数据进行修正
//        dto.getFromIndex();
        if(dto.getPageSize() <=0){
            dto.setPageSize(10);
        }
        if(dto.getPageNum() < 0){
            dto.setPageNum(0);
        }

        //3. 完成搜索
        SearchRequest searchRequest = new SearchRequest("app_info_article");

        //设置条件的构建器对象
        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();

        //创建一个复杂的bool查询
        BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery();

        if(StringUtils.isBlank(dto.getSearchWords())){
            booleanQuery.must(QueryBuilders.matchAllQuery());
        }else{
            QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR);
            booleanQuery.must(queryStringQueryBuilder);

            //记录用户搜索的关键字
            ApUser user = AppThreadLocalUtil.getUser();
            if(null != user){
                apUserSearchService.insert(dto.getSearchWords(), user.getId());
            }
        }

        if(null != dto.getMinBehotTime()){
            booleanQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        }

        //设置真正的查询条件
        sourceBulider.query(booleanQuery);

        //设置分页数据
        sourceBulider.from(dto.getFromIndex()).size(dto.getPageSize());

        searchRequest.source(sourceBulider);

        //设置高亮
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("title");
        highlighter.preTags("<font style='color: red; font-size: inherit;'>");
        highlighter.postTags("</font>");

        sourceBulider.highlighter(highlighter);

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        //4. 构建返回的参数并反馈

        SearchHit[] hits = response.getHits().getHits();
        List<Map> list = new ArrayList<>(hits.length);

        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);

            //解析高亮的数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();// 得到当前文档的所有的高亮(可能会再多个字段里面设置高亮)
            if(null != highlightFields && highlightFields.size() >0){
                Text[] titles = highlightFields.get("title").getFragments();

                map.put("h_title", titles[0].toString());
            }else{
                map.put("h_title", map.get("title"));
            }

            list.add(map);
        }

        return ResponseResult.okResult(list);
    }
}
